package com.rpay.service.mail.impl;

import com.rpay.common.dto.mail.MailDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.exception.UserException;
import com.rpay.common.util.LoggerUtil;
import com.rpay.dao.sms.SmsCodeDao;
import com.rpay.model.sms.SmsCodeDO;
import com.rpay.service.mail.IMailService;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/27
 * @version 1.0
 */
@Service
public class MailServiceImpl implements IMailService {
    @Autowired
    private JavaMailSenderImpl sender;

    @Autowired
    private FreeMarkerConfigurer configurer;

    @Autowired
    private SmsCodeDao smsCodeDao;

    @Value("${spring.mail.username}")
    private String username;
    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.hostIp}")
    private String hostIp;
    @Value("${spring.mail.debug}")
    private String debug;

    @Override
    public void send(MailDTO mail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(username);
        message.setTo(mail.getReceiver());
        message.setSubject(mail.getSubject());
        message.setText(mail.getContent());
        try {
            sender.send(message);
            LoggerUtil.info("send email to " + mail.getReceiver() + "success");
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtil.error("send email to " + mail.getReceiver() + "failed");
            throw new UserException(PcsResultCode.USER_MAIL_FAIL);
        }

    }


    @Override
    public void sendFreemarker(String templateName, MailDTO mail) {
        //发送成功将code存入数据库
        SmsCodeDO smsCodeDO = new SmsCodeDO();
        smsCodeDO.setCode(mail.getContent());
        smsCodeDO.setReceiver(mail.getReceiver());
        smsCodeDO.setVerifyType(mail.getVerifyType());
        smsCodeDO.setType("MAIL");
        int flag = smsCodeDao.insert(smsCodeDO);
        if(flag > 0) {
            String host = "smtp.gmail.com";
            int port = 465;
            sender.setUsername(username);//账号
            sender.setPassword(password);//密码
            sender.setDefaultEncoding("UTF-8");
            Properties properties = new Properties();
            properties.setProperty("mail.smtp.host", host);//设置端口
//            properties.setProperty("mail.transport.protocol", "smtp");//设置端口
            properties.setProperty("mail.smtp.ssl.enable", "true");//设置端口
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
            properties.setProperty("mail.smtp.port", Integer.toString(port));//设置端口
            properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(port));//设置ssl端口
            properties.setProperty("mail.debug", debug);//启用调试
//            properties.setProperty("mail.smtp.localhost", hostIp);//服务器地址
            properties.setProperty("mail.smtp.timeout", "5000");//设置链接超时

            properties.setProperty("mail.smtp.auth", "true");//开启认证
            sender.setJavaMailProperties(properties);


            MimeMessage message = sender.createMimeMessage();
            try {
                Template template = configurer.getConfiguration().getTemplate(templateName);
                MimeMessageHelper helper = new MimeMessageHelper(message, true);
                helper.setFrom(username);
                helper.setTo(mail.getReceiver());
                helper.setSubject(mail.getSubject());
                Map<String, Object> model = new HashMap<>();
                model.put("code", mail.getContent());
                String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
                helper.setText(text, true);
                sender.send(message);
                LoggerUtil.info("send email to " + mail.getReceiver() + " success");
            } catch (Exception e) {
                e.printStackTrace();
                LoggerUtil.error("send email to " + mail.getReceiver() + " failed");
                throw new UserException(PcsResultCode.USER_MAIL_FAIL);
            }
        } else {
            throw new UserException(PcsResultCode.ERROR_OPERATE);
        }

    }
}
